package com.example.nonggo.api;
import com.example.nonggo.bean.StreamResponse;
import com.example.nonggo.contract.QuestionContract;
import com.google.gson.Gson;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.Response;
import android.util.Log;

import java.io.IOException;

public class DeepSeekEventListener extends EventSourceListener {
   private static final String TAG = "DeepSeekEventListener";
   private Gson gson = new Gson();
   private QuestionContract callback;

   public DeepSeekEventListener(QuestionContract callback) {
      this.callback = callback;
   }

   @Override
   public void onEvent(EventSource eventSource, String id, String type, String data) {
      // 解析 JSON 数据
      StreamResponse response = gson.fromJson(data, StreamResponse.class);
      String answer = response.getAnswer(); // 提取 answer 字段

      // 打印日志
      Log.d(TAG, "Received answer: " + answer);

      // 更新 UI
      updateUI(answer);
   }

   private void updateUI(String answer) {
      callback.getQuestion(answer);
   }

   @Override
   public void onOpen(EventSource eventSource, Response response) {
      Log.d(TAG, "SSE connection opened");
   }

   @Override
   public void onClosed(EventSource eventSource) {
      Log.d(TAG, "SSE connection closed");
   }

   @Override
   public void onFailure(EventSource eventSource, Throwable t, Response response) {
//      Log.e(TAG, "SSE connection failed: " + t.getMessage());
      if (response != null) {
         Log.e(TAG, "Response code: " + response.code());
         try {
            Log.e(TAG, "Response body: " + response.body().string());
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

   }
}